package pers.cz.controller;

import com.alibaba.fastjson.JSON;
import pers.cz.model.RequestRecord;
import pers.cz.http.HttpUtils;
import pers.cz.service.SingleRequestService;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 单个请求调用
 * @program: PostGirl-panent
 * @description: SinglePostController
 * @author: Cheng Zhi
 * @create: 2021-03-13 14:40
 **/
@RestController
@Api(tags = "简单接口调用")
@RequestMapping(value = "/api/singleRequest")
public class SingleRequestController {

    @Autowired
    SingleRequestService service;

    /**
     * 处理post请求
     * @param map
     * @return
     */
    @ApiOperation(value = "处理post请求接口")
    @PostMapping(value = "/post")
    public String singlePost(@RequestBody Map map) {

        String request = (String) map.get("request");
        String url = (String) map.get("url");
        String response = HttpUtils.getResultByPost(request,url);

        return response;
    }

    /**
     * 处理get请求
     * @param map
     * @return
     */
    @ApiOperation(value = "处理get请求接口")
    @GetMapping(value = "/get")
    public String singleGet(@RequestBody Map map) throws IOException, URISyntaxException {

        String request = (String) map.get("request");
        String url = (String) map.get("url");
        JsonElement jsonElement = isJSON(request);
        if (jsonElement != null) {
            HashMap jsonMap = JSON.parseObject(request, HashMap.class);
            for (Object key : jsonMap.keySet()) {
                request = key + "=" + jsonMap.get(key) + "&";
            }
            request = request.substring(0,request.length() - 1);
        }
        String response = response = HttpUtils.getResultByGet(request,url);
        return response;
    }

    @ApiOperation(value = "后台请求分发器")
    @PostMapping(value = "/dispatcherRequest")
    public String dispatcherRequest(@RequestBody Map map, HttpServletRequest servletRequest) throws IOException, URISyntaxException {

        int userId = Integer.valueOf(servletRequest.getAttribute("userId").toString());
        String requestType = (String) map.get("type");
        String requestUrl = (String) map.get("url");
        String requestParam = (String) map.get("request");
        String originate = (String) map.get("originate");

        String replaceRequest = requestParam.replace(" ", "");
        // 将入参插入数据库
        service.insertRequestRecord(userId, requestUrl, replaceRequest, requestType, originate);
        // 将map中的type删除
        Iterator<String> iter = map.keySet().iterator();
        while(iter.hasNext()){
            if(iter.next().equals("type")){
                iter.remove();
            }
        }

        String request = "";
        // 如果是post请求
        if ("POST".equals(requestType)) {
            request = singlePost(map);
        }
        // 如果是get请求
        if ("GET".equals(requestType)) {
            request = singleGet(map);
        }

        return request;
    }

    @ApiOperation(value = "获取最近25条请求记录")
    @GetMapping(value = "/getRequestRecord")
    public List<RequestRecord> getRequestRecord() {

        return service.getRequestRecord();
    }

    /**
     * 判断字符串是否为json格式
     * @param str
     * @return
     */
    public static JsonElement isJSON(String str) {
        boolean result = false;
        JsonElement jsonEle = null;
        try {
            jsonEle = new JsonParser().parse(str);
            result = true;
        } catch (Exception e) {
            result=false;
        }
        if (result) {
            return jsonEle;
        }
        return null;
    }
}
